//
//  NewsDetailViewController.m
//  口袋
//
//  Created by dllo on 15/5/26.
//  Copyright (c) 2015年 口袋. All rights reserved.
//

#import "NewsDetailViewController.h"
#import "SANetWorkingTask.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "NewsDetailModel.h"
#import "CommentViewController.h"
#import "AppDelegate.h"
#import "WeiboSDK.h"
#import "DKNightVersion.h"

#define kAppKey @"1286675123"
#define kRedirectURI @"https://api.weibo.com/oauth2/default.html"

#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

@interface NewsDetailViewController ()

@property (nonatomic, assign) BOOL collect;

@end

@implementation NewsDetailViewController
- (void)dealloc
{
    
    [_docID release];
    [_dic release];
    [_note release];
    [_scroll release];
    [_model release];
    [super dealloc];
}


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.dic = [NSDictionary dictionary];
        self.rect = CGRectMake(0, 0, 0, 0);
        self.collect = NO;
    }
    return self;
}

- (void)loadView
{
    [super loadView];
    self.view.nightBackgroundColor = UIColorFromRGB(0x343434);
    [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(NSIntegerMin, NSIntegerMin) forBarMetrics:UIBarMetricsDefault];
    
    NSString *str = [NSString stringWithFormat:@"http://c.3g.163.com/nc/article/%@/full.html", self.docID];
    NSLog(@"url = %@", str);
    
    [SANetWorkingTask request:str parmater:nil block:^(NSDictionary *result) {
        self.dic = [result objectForKey:self.docID];
       self.note = [self filterHTML:[self.dic objectForKey:@"body"]];
        NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:20]};
        self.rect = [self.note  boundingRectWithSize:CGSizeMake(WIDTH - (0.027 * WIDTH) * 2, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
//        [self createNoteLabel];
        self.scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64)];
//        [self.scroll setContentSize:CGSizeMake(0, self.rect.size.height + 80 + 49)];
        [self.view addSubview:self.scroll];
        [self.scroll release];
        [self createLabel];
        [self createNoteLabel];
        [self.scroll setContentSize:CGSizeMake(0, self.rect.size.height + 0.1 * HEIGHT + 49 + self.height)];
        

#pragma mark -分享到微博
        UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(WIDTH / 6 * 5.3, HEIGHT / 30, WIDTH / 13, WIDTH / 13)];
        [button setImage:[UIImage imageNamed:@"share.png"] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"shareWhite.png"] forState:UIControlStateHighlighted];
        [button addTarget:self action:@selector(buttonAAct) forControlEvents:UIControlEventTouchUpInside];
        [self.scroll addSubview:button];
        [button release];
        
        
#pragma mark -收藏
        UIButton * collect = [[UIButton alloc] initWithFrame:CGRectMake(WIDTH / 6 * 5.23, HEIGHT / 11, WIDTH / 10, WIDTH / 10)];
        NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
        NSMutableArray * collectArray = [defaults objectForKey:@"collectArray"];
        
        for (NSDictionary * dic in collectArray) {
            NSString * title = [dic objectForKey:@"title"];
            NSString * title1 = [self.dic objectForKey:@"title"];
            
            if ([title isEqual:title1]) {
                [collect setImage:[UIImage imageNamed:@"bigBlue.png"] forState:UIControlStateNormal];
                [collect addTarget:self action:@selector(collectedAct) forControlEvents:UIControlEventTouchUpInside];
                [self.scroll addSubview:collect];
                [collect release];
                self.collect = YES;
            }
        }
        if (self.collect == NO) {
            [collect setImage:[UIImage imageNamed:@"blueStart.png"] forState:UIControlStateNormal];
            [collect addTarget:self action:@selector(collectAct) forControlEvents:UIControlEventTouchUpInside];
            [self.scroll addSubview:collect];
            [collect release];
        }
        
        
        // 右评论按钮
        NSString * count = [NSString stringWithFormat:@"%@跟帖", [self.dic objectForKey:@"replyCount"]];
        UIBarButtonItem * comments = [[UIBarButtonItem alloc] initWithTitle:count style:UIBarButtonItemStylePlain target:self action:@selector(commentAct)];
        [self.navigationItem setRightBarButtonItem:comments animated:YES];
        [comments release];
    }];
}

- (void)buttonAAct
{
    
    AppDelegate *myDelegate =(AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
    authRequest.redirectURI = kRedirectURI;
    authRequest.scope = @"all";
    
    WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:[self messageToShare] authInfo:authRequest access_token:myDelegate.wbtoken];
    request.userInfo = @{@"ShareMessageFrom": @"SendMessageToWeiboViewController",
                         @"Other_Info_1": [NSNumber numberWithInt:123],
                         @"Other_Info_2": @[@"obj1", @"obj2"],
                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
    //    request.shouldOpenWeiboAppInstallPageIfNotInstalled = NO;
    [WeiboSDK sendRequest:request];
    
}


#pragma mark -收藏的两个点击事件
- (void)collectAct
{
    
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    NSArray * arr = [defaults objectForKey:@"collectArray"];
    if (arr.count == 0) {
        NSMutableArray * collectArray = [NSMutableArray array];
        [collectArray addObject:self.dic];
        [defaults setObject:collectArray forKey:@"collectArray"];
        [defaults synchronize];
    } else {
        NSMutableArray * arrayy = [NSMutableArray arrayWithArray:arr];
        [arrayy addObject:self.dic];
        [defaults removeObjectForKey:@"collectArray"];
        [defaults setObject:arrayy forKey:@"collectArray"];
        [defaults synchronize];
    }
    
    [self loadView];
}

- (void)collectedAct
{
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    NSMutableArray * collectArray = [defaults objectForKey:@"collectArray"];
    NSMutableArray * collectArray1 = [NSMutableArray array];
    
    for (NSDictionary * dic in collectArray) {
        NSString * title = [dic objectForKey:@"title"];
        NSString * title1 = [self.dic objectForKey:@"title"];
        if (![title isEqual:title1]) {
            [collectArray1 addObject:dic];
        }
    }
    [defaults removeObjectForKey:@"collectArray"];
    [defaults setObject:collectArray1 forKey:@"collectArray"];
    [defaults synchronize];
    
    self.collect = NO;
    [self loadView];
}

- (WBMessageObject *)messageToShare
{
    NSString * title = [self.dic objectForKeyedSubscript:@"title"];
    
    WBMessageObject *message = [WBMessageObject message];
    
    message.text = NSLocalizedString(title, nil);
    
    WBImageObject *image = [WBImageObject object];
    image.imageData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Welcome" ofType:@"jpg"]];
    message.imageObject = image;
    
    return message;
}


#pragma mark -右评论按钮点击事件
- (void)commentAct
{
    CommentViewController *comment = [[CommentViewController alloc]init];
    comment.type = [self.dic objectForKey:@"replyBoard"];
    comment.docID = [self.dic objectForKey:@"docid"];
    [self.navigationController pushViewController:comment animated:YES];
    [comment release];
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    [self.view setBackgroundColor:[UIColor whiteColor]];

    
}

- (void)createLabel
{
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0.027 * WIDTH, 0.05 * WIDTH, WIDTH - (0.027 * 2 * WIDTH), 0.08 * WIDTH)];
    titleLabel.font = [UIFont boldSystemFontOfSize:21];
    //[self.titleLabel setBackgroundColor:[UIColor orangeColor]];
    titleLabel.text = [self.dic objectForKey:@"title"];
    titleLabel.nightTextColor = [UIColor lightGrayColor];
    [self.scroll addSubview:titleLabel];
    [titleLabel release];
    
    UILabel *timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(0.027 * WIDTH, 0.048* WIDTH + titleLabel.frame.size.height, WIDTH - (0.027 * 2 * WIDTH), 0.053 * WIDTH)];
    NSString *source = [self.dic objectForKey:@"source"];
    NSString *time = [self.dic objectForKey:@"ptime"];
    NSString *ptime = [NSString stringWithFormat:@"%@     %@", source,time];
    timeLabel.font = [UIFont systemFontOfSize:13];
    timeLabel.text = ptime;
    timeLabel.textColor = [UIColor grayColor];
    //[self.timeLabel setBackgroundColor:[UIColor orangeColor]];
    [self.scroll addSubview:timeLabel];
    [timeLabel release];
}

- (void)createNoteLabel
{
    NSArray *imageArray = [self.dic objectForKey:@"img"];
    if (imageArray.count) {
        self.height = 0.1 * HEIGHT + 64;
        for (int i = 0; i < imageArray.count; i++) {
            NSDictionary *dic = [imageArray objectAtIndex:i];
            NSString *a = [dic objectForKey:@"pixel"];
            NSArray *sizeArray = [a componentsSeparatedByString:@"*"];
            NSInteger last = [[sizeArray lastObject] integerValue];
            NSInteger first = [[sizeArray firstObject] integerValue];
            CGFloat size = (last * 1.0 / first * 1.0);
            if ([a length] != 0) {
                
                UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0.027 * WIDTH, self.height, WIDTH - (0.027 * 2 * WIDTH), size * WIDTH - (0.027 * 2 * WIDTH))];
                [imageView sd_setImageWithURL:[NSURL URLWithString:[dic objectForKey:@"src"]] placeholderImage:[UIImage imageNamed:@"loading.jpg"]];
                self.height += imageView.frame.size.height + 10;
                
                [self.scroll addSubview:imageView];
                [imageView release];
            }
            
        }
        UILabel *noteLabel = [[UILabel alloc]initWithFrame:CGRectMake(0.027 * WIDTH, self.height, WIDTH - (0.027 * 2 * WIDTH), self.rect.size.height)];
        noteLabel.numberOfLines = 0;
        noteLabel.text = self.note;
        noteLabel.font = [UIFont systemFontOfSize:20];
        noteLabel.nightTextColor = [UIColor lightGrayColor];
        [self.scroll addSubview:noteLabel];
        [noteLabel release];
        
    }else{
        UILabel *noteLabel = [[UILabel alloc]initWithFrame:CGRectMake(0.027 * WIDTH, 0.13 * HEIGHT, WIDTH - (0.027 * 2 * WIDTH), self.rect.size.height)];
        noteLabel.numberOfLines = 0;
        noteLabel.text = self.note;
        noteLabel.font = [UIFont systemFontOfSize:20];
        noteLabel.nightTextColor = [UIColor lightGrayColor];
        [self.scroll addSubview:noteLabel];
        [noteLabel release];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark -
#pragma mark 去掉HTML标签
- (NSString *)filterHTML:(NSString *)html
{
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString * text = @"p";
    while([scanner isAtEnd]==NO)
    {
        //找到标签的起始位置
        [scanner scanUpToString:@"<" intoString:nil];
        //找到标签的结束位置
        [scanner scanUpToString:@">" intoString:&text];
        //替换字符
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@"\n"];
    }
    //    NSString * regEx = @"<([^>]*)>";
    //    html = [html stringByReplacingOccurrencesOfString:regEx withString:@""];
    NSLog(@"%@", html);
    return html;
}


@end
